package com.sun.showcase.controller.basic;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.sun.showcase.biz.basic.service.FileDealService;
import com.sun.showcase.biz.basic.service.UploadFileService;
import com.sun.showcase.client.domain.basic.UploadFile;
import com.sun.showcase.client.query.basic.UploadFileQuery;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Result;
@Controller
@RequestMapping(value="/basic/uploadFile") 
public class UploadFileController {
	@Autowired
	private FileDealService fileDealService;
	@Autowired
	private UploadFileService uploadFileService;
	
	private Result json = new Result();
	/**
	 * 跳转到UploadFile管理页面
	 * 
	 * @return
	 */
	@RequestMapping(value="goUploadFile")
	public String goUploadFile() {
		return "basic/uploadFile";
	}
	//检索
	@ResponseBody
	@RequestMapping(value="listAll")
    public List<UploadFile> listAll(List<Long> ids){
    	return fileDealService.getByIds(ids);
    	
    }
	@ResponseBody
	@RequestMapping(value="saveAll")
    public Result saveAll(@RequestParam(value="type", defaultValue="0") String type,@RequestParam("root") String root,HttpServletRequest request){
    	
    	String filePath = null;//存储路径
    	UploadFile upload = null;//存储对象
    	List<UploadFile> list = new ArrayList<UploadFile>();
    			
    	if("0".equals(type)){//远程
    	   if(StringUtils.isNotBlank(root)){
    		   filePath = root;
    	   }else{
    		  filePath = "";
    	   }
 		   
 	    }
    	List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                 .getFiles("file");
        MultipartFile file = null;
    	int length = files.size();
    	
    	for(int i=0;i<length;i++){
    		file = files.get(i);
    		if (!file.isEmpty()) {
    			
    			upload = new UploadFile();
    			upload.setFileName(file.getOriginalFilename());
    			
    			upload.setType(Integer.parseInt(type));
    			upload.setFilePath(filePath);
    			
    			upload = fileDealService.saveFile(new File(file.getOriginalFilename()), upload);
	    	    list.add(upload);
    		}
    		json.setSuccess(true);
    		json.setData(list);
    		json.setMsg("添加成功！");
    	}
    	
 	   return json;
    }
	@ResponseBody
	@RequestMapping(value="saveFile")
    public Result saveFile(@RequestParam(value="type", defaultValue="0") String type,
    						@RequestParam("file") MultipartFile file){
       if (!file.isEmpty()) {
    	   UploadFile upload = new UploadFile();
    	   
    	   upload.setFileName(file.getOriginalFilename());
    	   
    	   upload.setType(Integer.parseInt(type));
    	   
    	   /*if("0".equals(type)){//远程
		   if(StringUtils.isBlank(location)) location = "A0101";
		   BaseseInfo baseseInfo =  baseseInfoService.getCode(location);
		   
		   upload.setFilePath(baseseInfo.getItemCodeCopy());
	   			}*/
    	   upload.setFilePath("/");
    	   	try {
				upload = fileDealService.saveFileAsStream(new BufferedInputStream(file.getInputStream()), upload);
				json.setSuccess(true);
				json.setData(upload);
				json.setMsg("添加成功！");
			} catch (IOException e) {
				json.setSuccess(false);
		    	json.setMsg("添加失败！");
			}
    	   
       }else{
    	   json.setSuccess(false);
    	   json.setMsg("添加失败！");
       }
	   return json;
    }
    
    //附件下载
	@RequestMapping(value="findAttach")
    public void findAttach(@RequestParam("id") String id,HttpServletResponse res){
    	
    	UploadFile uploadFile = fileDealService.findFile(id);
    	
    	res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + uploadFile.getSaveFileName());
        byte[] buff = new byte[1024];
        
        BufferedInputStream bis = null;
        OutputStream os = null;
    	
		try {
			os = res.getOutputStream();
			InputStream inputStream = fileDealService.findAttach(uploadFile);
			bis = new BufferedInputStream(inputStream);
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    }
    
	@ResponseBody
	@RequestMapping(value="deleteFile")
    public Result deleteFile(@RequestParam("id") String id){
    	fileDealService.deleteFile(id);
    	json.setSuccess(true);
		json.setMsg("成功！");
		return json;
    }
	
	/**
	 * 获得分页数据表格
	 */
	@ResponseBody
	@RequestMapping(value = "/datagrid")
	public DataGrid datagrid(UploadFileQuery uploadFileQuery) {
		return uploadFileService.datagrid(uploadFileQuery);
	}
}
